<template>
  <view class="login-container">
    <view class="login-content">
      <view class="logo-box">
        <image class="logo" src="/static/fishPiLogo.png" mode="aspectFit"></image>
        <text class="title">摸鱼派</text>
        <text class="subtitle">鱼油的专属社区</text>
      </view>

      <view class="form-box">
        <view class="input-group">
          <text class="label">用户名</text>
          <view class="input-wrapper">
            <input class="input" type="text" v-model="username" placeholder="请输入用户名" placeholder-class="placeholder" />
          </view>
        </view>

        <view class="input-group">
          <text class="label">密码</text>
          <view class="input-wrapper">
            <input class="input" type="password" v-model="password" placeholder="请输入密码"
              placeholder-class="placeholder" />
          </view>
        </view>

        <view class="input-group">
          <text class="label">两步验证码</text>
          <view class="input-wrapper">
            <input class="input" type="text" v-model="mfaCode" placeholder="未设置请留空" placeholder-class="placeholder" />
          </view>
        </view>

        <button class="login-btn" @click="handleLogin" :disabled="loading">
          {{ loading ? "登录中..." : "登 录" }}
        </button>

        <button class="scan-btn" @click="handleScanLogin">
          <text>扫码登录</text>
        </button>

        <view class="action-links">
          <text class="register-link" @click="handleRegister">注册账号</text>
          <text class="forgot-link" @click="handleForgotPassword">忘记密码?</text>
        </view>
      </view>

      <view class="geek-footer">
        <text class="footer-text">/* 代码改变世界 */</text>
      </view>
    </view>

    <!-- 隐私协议弹窗 -->
    <PrivacyModal :visible="showPrivacyModal" @agree="handlePrivacyAgree" @exit="handlePrivacyExit" />
  </view>
</template>

<script setup>
  import { ref, onMounted } from "vue";
  import api from "@/api";
  import { setApiKey, isLoggedIn } from "@/api";
  import FeatherIcon from "@/components/FeatherIcon.vue";
  import PrivacyModal from "@/components/PrivacyModal.vue";
  import {
    showLoading,
    hideLoading,
    showError,
    showSuccess,
    md5,
  } from "@/utils/common.js";

  // 表单数据
  const username = ref("");
  const password = ref("");
  const mfaCode = ref("");
  const loading = ref(false);

  // 隐私协议相关
  const showPrivacyModal = ref(false);

  // 检查隐私协议同意状态
  const checkPrivacyAgreement = () => {
    const privacyAgreed = uni.getStorageSync("privacy_agreed");
    console.log("privacyAgreed", privacyAgreed);

    if (!privacyAgreed) {
      console.log("用户未同意隐私协议，显示弹窗");
      // 延迟显示弹窗，确保页面加载完成
      setTimeout(() => {
        showPrivacyModal.value = true;
        console.log("弹窗状态设置为:", showPrivacyModal.value);
      }, 500);
    } else {
      console.log("用户已同意隐私协议，不显示弹窗");
      showPrivacyModal.value = false;
    }
  };

  // 处理隐私协议同意
  const handlePrivacyAgree = () => {
    console.log("收到同意事件");
    showPrivacyModal.value = false;
    // 保存用户同意状态
    uni.setStorageSync("privacy_agreed", true);
    console.log("用户已同意隐私协议");
  };

  // 处理隐私协议退出
  const handlePrivacyExit = () => {
    console.log("收到退出事件");
    // 退出应用
    // #ifdef APP-PLUS
    plus.runtime.quit();
    // #endif
    // #ifdef H5
    window.close();
    // #endif
  };

  // 扫码登录处理
  const handleScanLogin = () => {
    // 检查是否已登录
    if (isLoggedIn()) {
      showError("请先退出当前账号");
      return;
    }

    // 调用扫码API
    uni.scanCode({
      onlyFromCamera: false, // 允许从相册选择图片
      scanType: ["qrCode"], // 只扫描二维码
      success: async (res) => {
        const result = res.result;
        console.log("扫码结果:", result);

        if (result.startsWith("login:")) {
          // 处理登录二维码
          const token = result.split(":")[1];
          if (!token) {
            showError("无效的登录二维码");
            return;
          }

          try {
            showLoading("登录中");
            // 设置API密钥
            setApiKey(token);
            // 保存登录状态
            uni.setStorageSync("token", token);
            uni.setStorageSync("isLogin", true);

            showSuccess("登录成功");
            // 跳转到首页
            setTimeout(() => {
              uni.switchTab({
                url: "/pages/index/index",
              });
            }, 100);
          } catch (error) {
            console.error("扫码登录失败:", error);
            showError("登录失败，请重试");
          } finally {
            hideLoading();
          }
        } else {
          showError("无效的二维码");
        }
      },
      fail: (err) => {
        console.error("扫码失败:", err);
        // 检查是否是用户主动取消
        if (err.errMsg && err.errMsg.includes("cancel")) {
          console.log("用户取消扫码");
          return;
        }
        showError("扫码失败，请重试");
      },
    });
  };

  // 登录处理
  const handleLogin = async () => {
    // 表单验证
    if (!username.value) {
      showError("请输入用户名");
      return;
    }

    if (!password.value) {
      showError("请输入密码");
      return;
    }

    try {
      loading.value = true;
      showLoading("登录中");

      // 计算密码MD5（getKey接口需要MD5加密的密码）
      const md5Password = md5(password.value);

      // 调用登录API
      console.log("开始登录请求，用户名:", username.value);
      const res = await api.user.login(
        username.value,
        md5Password,
        mfaCode.value
      );
      console.log("登录请求结果:", res);

      // 请求成功，处理结果
      hideLoading();

      // 登录成功，保存API密钥
      if (res && res.code === 0) {
        // getKey接口返回的是Key字段
        setApiKey(res.Key);
        showSuccess("登录成功");

        // 跳转到首页
        setTimeout(() => {
          uni.switchTab({
            url: "/pages/index/index",
          });
        }, 100);
      } else {
        showError(res?.msg || "登录失败，请检查用户名或密码");
      }
    } catch (error) {
      console.error("登录发生错误:", error);
      hideLoading();

      let errorMsg = "登录失败，请检查网络或稍后再试";

      // 提取更明确的错误信息
      if (typeof error === "object") {
        if (error.message) {
          errorMsg = error.message;
        } else if (error.errMsg) {
          if (error.errMsg.includes("request:fail")) {
            errorMsg = "网络请求失败，请检查网络连接";
          } else {
            errorMsg = error.errMsg;
          }
        }
      }

      showError(errorMsg);

      // 在开发环境下显示更详细的错误
      if (process.env.NODE_ENV === "development") {
        console.log("详细错误信息:", JSON.stringify(error, null, 2));
        console.log("当前环境:", process.env.NODE_ENV);
        console.log("请检查api.js和vite.config.js中的配置是否正确");
      }
    } finally {
      loading.value = false;
    }
  };

  // 忘记密码处理
  const handleForgotPassword = () => {
    // 跳转到外部浏览器
    uni.showModal({
      title: "提示",
      content: "将跳转到摸鱼派官网重置密码",
      success: (res) => {
        if (res.confirm) {
          // 使用系统浏览器打开重置密码页面
          plus.runtime.openURL("https://fishpi.cn/settings/account");
        }
      },
    });
  };

  // 注册账号处理
  const handleRegister = () => {
    // 使用 webview 打开注册页面
    uni.navigateTo({
      url: `/pages/webview/webview?url=${encodeURIComponent("https://fishpi.cn/register")}`
    });
  };

  // 页面加载时检查隐私协议
  onMounted(() => {
    checkPrivacyAgreement();
  });
</script>

<style lang="scss">
  .login-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #121212;
    background-image: radial-gradient(circle at 15% 50%,
        rgba(36, 36, 36, 0.5) 0%,
        transparent 20%),
      radial-gradient(circle at 85% 30%,
        rgba(36, 36, 36, 0.5) 0%,
        transparent 20%);
  }

  .login-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 85%;
    padding: 30rpx 0;
  }

  .logo-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 60rpx;

    .logo {
      width: 160rpx;
      height: 160rpx;
      margin-bottom: 30rpx;
    }

    .title {
      font-size: 52rpx;
      font-weight: bold;
      color: #ffffff;
      margin-bottom: 10rpx;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }

    .subtitle {
      font-size: 28rpx;
      color: #f0d35e;
      letter-spacing: 2rpx;
    }
  }

  .form-box {
    width: 100%;
    background-color: rgba(30, 30, 30, 0.8);
    border-radius: 16rpx;
    padding: 50rpx 40rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);

    .input-group {
      margin-bottom: 40rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-bottom: 16rpx;
        font-family: "Menlo", "Monaco", monospace;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        transition: border 0.3s ease;
        padding-bottom: 10rpx;

        &:focus-within {
          border-bottom: 1px solid #f0d35e;
        }

        .iconfont {
          font-size: 32rpx;
          color: #f0d35e;
          margin-right: 20rpx;
        }
      }

      .input {
        flex: 1;
        height: 80rpx;
        font-size: 32rpx;
        color: #ffffff;
        background: transparent;
        font-family: "Menlo", "Monaco", monospace;
      }

      .placeholder {
        color: rgba(255, 255, 255, 0.4);
      }
    }

    .login-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      background-color: #f0d35e;
      color: #121212;
      font-size: 32rpx;
      font-weight: bold;
      border-radius: 8rpx;
      margin-top: 30rpx;
      letter-spacing: 2rpx;
      box-shadow: 0 4rpx 12rpx rgba(240, 211, 94, 0.3);
      transition: all 0.3s ease;

      &:after {
        border: none;
      }

      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 6rpx rgba(240, 211, 94, 0.2);
      }

      &[disabled] {
        background-color: rgba(240, 211, 94, 0.5);
        color: rgba(18, 18, 18, 0.7);
      }
    }

    .scan-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      background-color: rgba(255, 255, 255, 0.1);
      color: #ffffff;
      font-size: 32rpx;
      border-radius: 8rpx;
      margin-top: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      border: 1px solid rgba(255, 255, 255, 0.2);
      transition: all 0.3s ease;

      &:after {
        border: none;
      }

      &:active {
        background-color: rgba(255, 255, 255, 0.2);
      }

      .scan-icon {
        font-size: 36rpx;
      }
    }

    .action-links {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      font-size: 26rpx;

      .register-link,
      .forgot-link {
        color: #f0d35e;
        text-decoration: none;
        position: relative;

        &:after {
          content: "";
          position: absolute;
          bottom: -4rpx;
          left: 0;
          width: 100%;
          height: 1px;
          background: #f0d35e;
          transform: scaleX(0);
          transform-origin: right center;
          transition: transform 0.3s ease;
        }

        &:hover:after {
          transform: scaleX(1);
          transform-origin: left center;
        }
      }
    }
  }

  .geek-footer {
    margin-top: 60rpx;
    text-align: center;

    .footer-text {
      font-family: "Menlo", "Monaco", monospace;
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.5);
    }
  }

  @font-face {
    font-family: "iconfont";
    src: url("data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAQMAAsAAAAACGQAAAO/AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDHAqELINxATYCJAM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MD7bbDnGHHAkLiYgrRC6wwpViQpIvKPOsFVX0c5U2KgugCu1nP0NyMJdTrxMFcTJHYKCYwPMeW0OswDAqymcQcC8fYfZiQTQmiT9IiMpkodz1N/3pdpKoPXRjDRCFkC5SCLCEpqVAyHssFqvr6OIpnohBR/UPYmXkZ1GyMjReqI4YTExPV2tpYbcLwOGwSegpDAhFIjREmWeBY3H4whFgpgpqcRFqImkrkavcGU9r1RtPf94Bo13EkR4msQmHgOilx7tRoAwA=") format("woff2");
  }

  .iconfont {
    font-family: "iconfont" !important;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }

  .icon-user:before {
    content: "\e7ae";
  }

  .icon-lock:before {
    content: "\e7c9";
  }
</style>